package easier.app.x.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.graphics.RectF;
import android.util.AttributeSet;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;

/**
 * Android 圆角图片
 */
public class RoundedImageView extends AppCompatImageView {

    private final Path mPath = new Path();
    private final RectF mRectF = new RectF();
    /**
     * 圆角数据
     */
    private final float[] mCorners = new float[8];

    public RoundedImageView( @NonNull Context context ) {

        super( context );
    }

    public RoundedImageView( @NonNull Context context, @Nullable AttributeSet attrs ) {

        super( context, attrs );
    }

    public RoundedImageView( @NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr ) {

        super( context, attrs, defStyleAttr );
    }

    @Override
    protected void onSizeChanged( int w, int h, int oldw, int oldh ) {

        super.onSizeChanged( w, h, oldw, oldh );
        mRectF.set( 0, 0, w, h );
    }

    public void setCorners( float leftTop, float rightTop, float rightBottom, float leftBottom ) {

        mCorners[0] = leftTop;
        mCorners[1] = leftTop;
        mCorners[2] = rightTop;
        mCorners[3] = rightTop;
        mCorners[4] = rightBottom;
        mCorners[5] = rightBottom;
        mCorners[6] = leftBottom;
        mCorners[7] = leftBottom;
    }

    public void setCorners( float[] corners ) {

        System.arraycopy( corners, 0, mCorners, 0, corners.length );
    }

    @Override
    protected void onDraw( Canvas canvas ) {

        mPath.reset();
        mPath.addRoundRect( mRectF, mCorners, Direction.CW );
        canvas.clipPath( mPath );
        super.onDraw( canvas );
    }
}
